package com.hailin.lease.web.app.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hailin.lease.common.constant.RedisConstant;
import com.hailin.lease.common.exception.LeaseException;
import com.hailin.lease.common.result.ResultCodeEnum;
import com.hailin.lease.common.utils.CodeUtil;
import com.hailin.lease.common.utils.JwtUtil;
import com.hailin.lease.model.entity.UserInfo;
import com.hailin.lease.model.enums.BaseStatus;
import com.hailin.lease.web.app.mapper.LoginMapper;
import com.hailin.lease.web.app.service.LoginService;
import com.hailin.lease.web.app.service.SmsService;
import com.hailin.lease.web.app.vo.user.LoginVo;
import com.hailin.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: yuhailin
 * @description 登录
 * @date: 2024/8/5 17:03
 */


@Service
public class LoginServiceimpl extends ServiceImpl<LoginMapper, UserInfo> implements LoginService{

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private LoginMapper loginMapper;
    /**
     * 获取短信验证码
     * @param phone
     */
    public void getCode(String phone) {
        log.debug("获取短信验证码："+phone);
        String code = CodeUtil.getCode(6);
        String key = RedisConstant.APP_LOGIN_PREFIX+phone;
        Boolean isExist = redisTemplate.hasKey(key);
        if (Boolean.TRUE.equals(isExist)) {
            Long ttl = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            if(RedisConstant.APP_LOGIN_CODE_TTL_SEC- ttl < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        smsService.sendCode(phone, code);
        log.debug("发送验证码："+code);
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    /**
     * 登录
     * @param loginVo
     * @return
     */
    public String login(LoginVo loginVo) {
        //1.校验是否未空
        if(loginVo.getPhone()==null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if(loginVo.getCode()==null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //2.校验验证码
        String key = RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        String code = redisTemplate.opsForValue().get(key);
        if(code==null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if(!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        UserInfo userInfo = super.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, loginVo.getPhone()));
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户"+loginVo.getPhone().substring(6));
            super.save(userInfo);
        }
        if(userInfo.getStatus().equals(BaseStatus.DISABLE)) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        return JwtUtil.createToken(userInfo.getId(), userInfo.getNickname());
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    public UserInfoVo getUserInfoById(Long userId) {
        UserInfo userInfo = super.getById(userId);
        return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }
}
